import 'package:dio/dio.dart';
// import 'package:get/get.dart' as getx;

import '../../data/local/local_storage.dart';
import '../../utils/dialog_utils.dart';
import '../../utils/my_logger.dart';
import '../../utils/toast_utils.dart';
import '../../widget/loading_dialog.dart';
import 'network_code.dart';
import 'resource.dart';

class ResponseInterceptors extends InterceptorsWrapper {
  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) async {
    RequestOptions option = response.requestOptions;
    late Resource value;
    try {
      var header = response.headers[Headers.contentTypeHeader];
      if ((header != null && header.toString().contains("text"))) {
        value = Resource.success(response.data['Data']);
      } else if (response.statusCode! >= 200 && response.statusCode! < 300) {
        print('respons1222e.data==>${response.data}');
        var code = response.data['code'];
        if (code == 200) {
          var data = response.data['data'];
          print('data32111==>$data');
          value = Resource.success(data, message: response.data['msg']);
        } else {
          String message = response.data['msg'];
          print('response.data==>${response.data}');
          // ToastUtils.show(message);
          // if (code == 401) {
          //   // eventBus.fire(HttpErrorEvent(NetworkCode.unauthorized, '登录过期,请重新登录'));
          //   await LocalStorage.setToken(null);
          //   value = Resource.error(NetworkCode.unauthorized, message);
          //   getx.Get.offAll(() => VerifyCodeLoginPage());
          // }
          // DialogUtils.showAlert(title: message);
          value = Resource.error(code, message);
        }
      } else {
        print('response111===>$response');
        String message = response.data['msg'];
        ToastUtils.show(message);
      }
    } catch (e) {
      MyLogger.d(e.toString() + option.path);
      value = Resource.error(NetworkCode.networkError, '');
    }
    response.data = value;
    return handler.next(response);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    print('er32321321r===>${err}');
    String _msg = err.response!.data['msg'];
    // print('err-response===>${err.response.msg}');

    if (err.response?.statusCode == 401) {
      // LocalStorage.setToken(null);
      SharedPreferencesManager().setToken('');
      // getx.Get.offAll(() => VerifyCodeLoginPage());
    } else {
      DialogUtils.showAlert(title: '错误提示框', content: _msg);
    }
    LoadingDialog.dismiss();

    return handler.next(err);
  }
}
